﻿/// <reference path="jquery-1.8.1-vsdoc.js" />

/*

*Conjee UI Solution Create data 2012/07/03

*Version:0.1

*Base Goal, Core helper. Form control completed. text box, text area, dropdown list, checkbox, radio, button.. plugin timer.

*level 1: validate, submit, view model to html control.

*level 2:  slider, layout, pagination, data grid, dialog.

*level 3: my animations.

*/

/*String format.*/
String.stringFormat = function () {

    //get the arguments, first one is the string format and cannot be null.
    if (arguments.length == 0) {
        return null;
    }

    //Create string format
    var result = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var format = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        result = result.replace(format, arguments[i]);
    }

    return result;
}

/* CUI core */
var CUICore = {

    animateTime: 500,

    //the absolute path of web site root 
    webRoot: "",

    //Is debug 
    debug: true,

    //the localization resource file cache.
    localization: { current: "", resource: null },

    //validate type define
    validateType: { number: "number", phone: "phone", email: "email" },

    //error type define
    errorType: { exception: "exception", requireError: "requireError", lengthError: "lengthError", validateError: "validateError" },

    //render type define
    renderType: { html: "html", before: "before", after: "after", prepend: "prepend", append: "append" },

    pluginType: { cDropdownList: 1, cTextbox: 2, cCheckbox: 3, cRadioGroup: 4, cTextarea: 5, cButton: 6, unkonw: 0 },

    errorMessage: {
        //default exception error define
        defaultExceptionError: "Unknow exception!",

        //default require error define
        defaultRequireError: "This field is required.",

        //default require error define
        defaultMaxLengthError: "Please enter no more than {0} characters.",

        //default length error define
        defaultMinLengthError: "Please enter at least {0} characters.",

        //default validate error define
        defaultValidateError: " Validate error.",

        //email validate error define
        emailValidateError: "Invalid Input. Please enter a valid email",

        //number validate error define
        numberlValidateError: "Please enter a valid number."
    }
};

//base html control attribute options define
CUICore.baseControlOption = {

    //control render type, default is html
    renderType: CUICore.renderType.html,

    //Tip text
    tip: null,

    //the control skin
    skin: null,

    width: null,

    //can copy the value
    disableCopy: false,

    attribute: {
        //control Id
        id: null,

        //control name
        name: null,

        //Control class
        "class": null,

        //control default value
        "value": null,

        //Required error message
        RequiredErrorMessage: null,

        //Length error message
        LengthErrorMessage: null,

        //Validate error message
        ValidateErrorMessage: null,

        //Common error message
        CommonErrorMessage: null,

        doValidate: true,

        //control validate type, default is string
        validateType: null,

        //before render control
        beforeRender: null,

        //after render control
        afterRender: null,

        //on item focusin
        onItemFocusin: null,

        //on item focusout
        onItemFocusout: null,

        //on item mouse over
        onItemMouseover: null,

        //on item mouse out
        onItemMouseout: null,

        //on validate error
        OnValidateError: null,

        //on validate pass
        OnValidatePass: null
    }
};

function CUIPage() {

    //Page initial method
    if (typeof this.addEvent != "function") {
        //all of the events in the page are in here
        CUIPage.prototype.pageEvent = {};
        CUIPage.prototype.pageData = {};

        //Add events for page
        CUIPage.prototype.addEvent = function () {

            //For tip
            $("[tip]").live("focusin", function () {
                var self = $(this);
                var kind = self.kind();
                if (kind == CUICore.pluginType.cTextbox || kind == CUICore.pluginType.cTextarea) {
                    if (self.hasClass("tip")) {
                        self.val("");
                        self.removeClass("tip");
                    }
                }
            });

            $("[tip]").live("focusout", function () {
                var self = $(this);
                var kind = self.kind();
                if (kind == CUICore.pluginType.cTextbox || kind == CUICore.pluginType.cTextarea) {
                    if (!self.getValue() && self.getValue().length == 0) {
                        self.val(self.attr("tip"));
                        self.addClass("tip");
                    }
                }
            });

            //Add click event for element which has [onItemClick] attribute
            $("[onItemClick]").live("click", function () {
                var self = $(this);
                var eventName = self.attr("onItemClick");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Click event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onItemFocusin] attribute
            $("[onItemFocusin]").live("focusin", function () {
                var self = $(this);
                var eventName = self.attr("onItemFocusin");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Focusin event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onItemFocusin] attribute
            $("[onItemKeyup]").live("keyup", function () {
                var self = $(this);
                var eventName = self.attr("onItemKeyup");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Focusin event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onItemFocusout] attribute
            $("[onItemFocusout]").live("focusout", function () {
                var self = $(this);
                var eventName = self.attr("onItemFocusout");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Focusout event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onItemMouseover] attribute
            $("[onItemMouseover]").live("mouseover", function () {
                var self = $(this);
                var eventName = self.attr("onItemMouseover");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Focusout event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onItemMouseout] attribute
            $("[onItemMouseout]").live("mouseout", function () {
                var self = $(this);
                var eventName = self.attr("onItemMouseout");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Mouseout event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add click event for element which has [onChanged] attribute
            $("[onChanged]").live("change", function () {
                var self = $(this);
                var eventName = self.attr("onChanged");
                if (typeof CUIPage.prototype.pageEvent[eventName] == "function") {
                    CUIPage.prototype.pageEvent[eventName].call(this, self);
                }
                else {
                    if (CUICore.debug) {
                        alert(String.stringFormat("Changed event {0} cannot be found in current context!", eventName));
                    }
                }
            });

            //Add validate for CUI
            $("[doValidate='true']").live("change", function () {
                var self = $(this);
                CUIPage.prototype.ShowValidate(self);
            });
        };

        //show the validate result
        CUIPage.prototype.ShowValidate = function ($element) {
            var validateResult = CUIPage.prototype.ValidateCore($element);
            var id = "";
            var kind = $element.kind();
            if (kind == CUICore.pluginType.cRadioGroup) {
                id = $element.attr("name");
            }
            else {
                id = $element.attr("id");
            }
            var $validate_error = $("[validate_error='" + id + "']");

            if (validateResult !== true) {
                $element.closest(".cui").addClass("cui-error");
                if ($validate_error.length == 0) {
                    alert(validateResult);
                }
                else {
                    $validate_error.text(validateResult).removeClass("visible");
                }
                var errorEventName = $element.attr("OnValidateError");
                if (typeof CUIPage.prototype.pageEvent[errorEventName] == "function") {
                    CUIPage.prototype.pageEvent[errorEventName].call(this, $element);
                }
                return false;
            }
            else {
                $element.closest(".cui").removeClass("cui-error");
                $validate_error.addClass("visible");
                var passEventName = $element.attr("OnValidatePass");
                if (typeof CUIPage.prototype.pageEvent[passEventName] == "function") {
                    CUIPage.prototype.pageEvent[passEventName].call(this, $element);
                }
                return true;
            }
        };

        //Initial validate according to the attribute
        CUIPage.prototype.ValidateCore = function ($element) {

            if (!$element.hasClass("hide") && !$element.is(":disabled")) {
                //Get the value of input
                var value = $element.getValue();

                //required validate [required validate will not validate checkbox]
                if (!$element.is("input:checkbox")) {
                    if ($element.is("[required]")) {
                        if (value === undefined || value === null || value === "") {
                            if ($element.is("[RequiredErrorMessage]")) {
                                return $element.attr("RequiredErrorMessage");
                            }
                            else {
                                if ($element.is("[CommonErrorMessage]")) {
                                    return $element.attr("CommonErrorMessage");
                                }
                                else {
                                    return CUICore.errorMessage.defaultRequireError;
                                }
                            }
                        }

                    } else {
                        //if it is not required, and value is null, returen true
                        if (value === undefined || value === null || value === "") {
                            return true;
                        }
                    }
                }


                //Min Length validate [Min length only validate text box & text area]
                if ($element.is("input:text") || $element.is("textarea")) {
                    //Mini Length validate
                    if ($element.is("[minlength]")) {

                        //get the minlength value
                        var minlength = Number($element.attr("minlength"));

                        if (isNaN(minlength) || value.length < minlength) {
                            //Min length error
                            if ($element.is("[LengthErrorMessage]")) {
                                return $element.attr("LengthErrorMessage");
                            }
                            else {
                                if ($element.is("[CommonErrorMessage]")) {
                                    return $element.attr("CommonErrorMessage");
                                }
                                else {
                                    return String.stringFormat(CUICore.errorMessage.defaultMinLengthError, minlength);
                                }
                            }
                        }
                    }
                }

                //Max Length validate [Maxlength only validate text area]
                if ($element.is("textarea") && $element.is("[maxlength]")) {

                    //get the maxlength value
                    var maxlength = Number($element.attr("maxlength"));

                    if (isNaN(maxlength) || value.length > maxlength) {
                        //Max length error
                        if ($element.is("[LengthErrorMessage]")) {
                            return $element.attr("LengthErrorMessage");
                        }
                        else {
                            if ($element.is("[CommonErrorMessage]")) {
                                return $element.attr("CommonErrorMessage");
                            }
                            else {
                                return String.stringFormat(CUICore.errorMessage.defaultMaxLengthError, maxlength);
                            }
                        }
                    }
                }

                //Validate type
                if ($element.is("[validatetype]")) {
                    var reg;
                    var type = $element.attr("validatetype");
                    var errorString = true;
                    switch (type) {
                        case CUICore.validateType.phone:
                        case CUICore.validateType.number:
                            reg = /^[0-9]*$/;
                            if (!reg.test(value)) {
                                errorString = CUICore.errorMessage.numberlValidateError;
                            }
                            break;
                        case CUICore.validateType.email:
                            reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
                            if (!reg.test(value)) {
                                errorString = CUICore.errorMessage.emailValidateError;
                            }
                            break;
                        default:
                            if (typeof CUIPage.prototype.pageEvent[type] == "function") {
                                errorString = CUIPage.prototype.pageEvent[type].call(this, $element);
                            }
                            else {
                                errorString = eval(type);
                            }
                            break;
                    }
                    if (errorString !== true) {
                        if ($element.is("[ValidateErrorMessage]")) {
                            return $element.attr("ValidateErrorMessage");
                        }
                        else {
                            if ($element.is("[CommonErrorMessage]")) {
                                return $element.attr("CommonErrorMessage");
                            }
                            else {
                                return errorString;
                            }
                        }
                    }
                }
            }
            return true;
        };

        //Initial Page
        CUIPage.prototype.InitialPage = function () {
            CUIPage.prototype.addEvent();
        };
    }
}


/******************************************************************************/
/****************************** CUI PLUGINS ******************************/
/******************************************************************************/

(function ($) {

    /****************************** FROM CONTROLS ******************************/

    //Text box control
    $.fn.cTextbox = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //is password text box 
            password: false,
            //default width
            width: "180px",
            //the skin of text box
            skin: '<div class="cui cui-textbox">{0}</div>',
            attribute: {
                //is required. If has attribute minlength, required is useless.
                required: null,
                //the minlength of text box.
                minlength: null,
                //the maxlength of text box
                maxlength: null,
                //on value change
                onChanged: null
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        if (opts.password) {
            opts.core_html = '<input type="password" {0} />';
        }
        else {
            opts.core_html = '<input type="text" {0} />';
        }

        return renderHtml(self, opts, CUICore.pluginType.cTextbox);
    };

    //Dropdown list control
    $.fn.cDropdownList = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //the core html of dropdown list
            core_html: "<select {0} >{1}</select>",
            //allow to multiple select
            multiple: false,
            //default width
            width: "190px",
            //the default selected item value
            selected: null,
            //the select items
            data: null,
            //the skin of dropdown list 
            skin: '<div class="cui cui-dropdownList">{0}</div>',
            attribute: {
                //is required.
                required: null,
                //on value change
                onChanged: null
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        return renderHtml(self, opts, CUICore.pluginType.cDropdownList);
    };

    //checkbox control
    $.fn.cCheckbox = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //the core html of checkbox
            core_html: '<input type="checkbox" {0} />',
            //the skin of checkbox
            skin: '<div class="cui cui-checkbox">{0}</div>',
            attribute: {
                //is checked
                checked: null,
                //on value change
                onChanged: null
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        return renderHtml(self, opts, CUICore.pluginType.cCheckbox);
    };

    //radio button control
    $.fn.cRadioGroup = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //the core html of radio button
            core_html: '<input type="radio" {0} id="{1}" name={2} value="{3}" /><label for="{1}">{4}</label>',
            //the radio button items
            data: null,
            //the skin of radio button group
            skin: '<div class="cui cui-radio">{0}</div>',
            attribute: {
                //is required.
                required: null,
                //on value change
                onChanged: null
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        //avoid adding id for radio button group, for the radio button
        if (opts.attribute.id !== null) {
            if (opts.attribute.name === null) {
                opts.attribute.name = opts.attribute.id;
                opts.attribute.id = null;
            }
        }

        return renderHtml(self, opts, CUICore.pluginType.cRadioGroup);
    };

    //Text area control
    $.fn.cTextarea = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //the core html of text area
            core_html: "<textarea {0} >{1}</textarea>",
            //default width
            width: "350px",
            //default height
            height: "150px",
            //the skin of text area
            skin: '<div class="cui cui-textarea">{0}</div>',
            attribute: {
                //is required. If has attribute minlength, required is useless.
                required: null,
                //the minlength of text area.
                minlength: null,
                //the maxlength of text area
                maxlength: null,
                //on value change
                onChanged: null
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        return renderHtml(self, opts, CUICore.pluginType.cTextarea);
    };

    //Button control
    $.fn.cButton = function (options) {
        var self = $(this);
        //defined default options
        var defaults = {
            //the core html of button
            core_html: "<a {0} >{1}</a>",
            //the default text of button
            tip: "OK",
            //the skin of button
            skin: '<div class="cui cui-button">{0}</div>',
            attribute: {
                //the default href of button
                href: "#none",
                //on button click
                onItemClick: null,
                //the button not support validate
                doValidate: false
            }
        };

        //inherit base control option
        var opts = merginOptions(defaults, options);

        return renderHtml(self, opts, CUICore.pluginType.cButton);
    };

    function merginOptions(defaults, options) {
        //inherit base control option
        defaults.attribute = $.extend({}, CUICore.baseControlOption.attribute, defaults.attribute);
        defaults = $.extend({}, CUICore.baseControlOption, defaults);

        //Get the options
        var attr = $.extend({}, defaults.attribute, options.attribute);
        var opts = $.extend({}, defaults, options);
        opts.attribute = attr;

        return opts;
    }

    function renderHtml($obj, opts, type) {

        //Create html
        var htmlstring;

        htmlstring = createHtml($obj, opts, type);

        if (typeof opts.beforeRender == "function") {
            opts.beforeRender($obj);
        }

        var returnValue = $(htmlstring);
        //Render html
        switch (opts.renderType) {
            case CUICore.renderType.html: $obj.html(""); $obj.append(returnValue); returnValue.hide().fadeIn(CUICore.animateTime); break;
            case CUICore.renderType.before: $obj.before(returnValue); returnValue.hide().fadeIn(CUICore.animateTime); break;
            case CUICore.renderType.after: $obj.after(returnValue); returnValue.hide().fadeIn(CUICore.animateTime); break;
            case CUICore.renderType.prepend: $obj.prepend(returnValue); returnValue.hide().fadeIn(CUICore.animateTime); break;
            case CUICore.renderType.append: $obj.append(returnValue); returnValue.hide().fadeIn(CUICore.animateTime); break;
        }
        if (typeof opts.afterRender == "function") {
            afterRender($obj);
        }
        return returnValue.find("[kind]");
    }

    function createHtml($obj, opts, type) {
        if (opts) {

            // the core string
            var htmlCoreString = "";

            //the total html string
            var htmlstring = "";

            //create the attributes
            var attrString = ' kind="' + type + '" ';

            if (type == CUICore.pluginType.cTextbox || type == CUICore.pluginType.cTextarea) {
                if (opts.tip !== null && opts.attribute.value === null) {
                    opts.attribute.value = opts.tip;
                    opts.attribute.class += " tip";
                }
            }

            $.each(opts.attribute, function (key, value) {
                if (value !== null) {
                    attrString += key + '="' + value + '" ';
                }
            });

            if (opts.disableCopy) {

                attrString += ' oncopy="javascript:return false;" oncut="javascript:return false;" ';
            }

            //create the child elements
            var elementString = "";
            switch (type) {

                case CUICore.pluginType.cTextbox:
                    //width
                    if (opts.width !== null) {
                        attrString += ' style="width:' + opts.width + '"';
                    }
                    if (opts.tip !== null) {
                        attrString += ' tip="' + opts.tip + '"';
                    }
                    //the core html of text box
                    htmlCoreString = opts.core_html;
                    //Join attrString and elementString with core html template
                    htmlstring = String.stringFormat(htmlCoreString, attrString);
                    break;

                case CUICore.pluginType.cDropdownList:
                    //width
                    if (opts.width !== null) {
                        attrString += 'style="width:' + opts.width + '"';
                    }
                    //the core html of dropdown list
                    htmlCoreString = opts.core_html;
                    //set the default tip item
                    if (opts.tip !== null) {
                        if (opts.selected === null) {
                            elementString += '<option value="" selected="selected">' + opts.tip + '</option>';
                        }
                        else {
                            elementString += '<option value="">' + opts.tip + '</option>';
                        }
                    }
                    //create other items in data 
                    if (opts.data !== null) {
                        $.each(opts.data, function (key, value) {
                            if (opts.selected === key) {
                                elementString += '<option value="' + key + '" selected="selected" >' + value + '</option>';
                            }
                            else {
                                elementString += '<option value="' + key + '">' + value + '</option>';
                            }
                        });
                    }
                    //Join attrString and elementString with core html template
                    htmlstring = String.stringFormat(htmlCoreString, attrString, elementString);
                    break;

                case CUICore.pluginType.cCheckbox:
                    //the core html of checkbox
                    htmlCoreString = '<input type="checkbox" {0} />';
                    //Join attrString and elementString with core html template
                    htmlstring = String.stringFormat(htmlCoreString, attrString);
                    //set the default tip item
                    if (opts.tip !== null && opts.attribute.id !== null) {
                        var labelString = '<label for="{0}">{1}</label>';
                        htmlstring += String.stringFormat(labelString, opts.attribute.id, opts.tip);
                    }
                    break;

                case CUICore.pluginType.cRadioGroup:
                    //the core html of radio button
                    htmlCoreString = opts.core_html;
                    selectedhtmlCoreString = '<input type="radio" {0} id="{1}" name={2} value="{3}" checked="checked" /><label for="{1}">{4}</label>';

                    //set the default tip item
                    if (opts.data !== null) {
                        var i = 0;
                        $.each(opts.data, function (key, value) {
                            if (opts.selected !== key) {
                                htmlstring += String.stringFormat(htmlCoreString, attrString, opts.attribute.name + i.toString(), opts.attribute.name, key, value);
                            }
                            else {
                                htmlstring += String.stringFormat(selectedhtmlCoreString, attrString, opts.attribute.name + i.toString(), opts.attribute.name, key, value);
                            }
                            i++;
                        });
                    }
                    break;

                case CUICore.pluginType.cTextarea:
                    //set width & height
                    attrString += 'style="width:' + opts.width + '; height:' + opts.height + '";';
                    if (opts.tip !== null) {
                        attrString += 'tip="' + opts.tip + '"';
                    }
                    //the core html of text area
                    htmlCoreString = '<textarea {0} >{1}</textarea>';
                    //Join attrString and elementString with core html template
                    if (opts.tip !== null) {
                        elementString = opts.tip;
                    }
                    htmlstring = String.stringFormat(htmlCoreString, attrString, elementString);
                    break;

                case CUICore.pluginType.cButton:
                    //the core html of button
                    htmlCoreString = '<a {0} >{1}</a>';
                    if (opts.tip !== null) {
                        elementString = opts.tip;
                    }
                    htmlstring = String.stringFormat(htmlCoreString, attrString, elementString);
                    break;
            }

            if (opts.skin != null) {
                htmlstring = String.stringFormat(opts.skin, htmlstring);
            }

            return htmlstring;
        }
        else {
            if (CUICore.debug) {
                alert("The option cannot be empty!");
            }
        }
    }

    /****************************** getValue method of CONTROLS ******************************/
    $.fn.kind = function () {
        if ($(this).is("[kind]")) {
            var kind = parseInt($(this).attr("kind"));
            switch (kind) {
                case CUICore.pluginType.cTextbox:
                case CUICore.pluginType.cDropdownList:
                case CUICore.pluginType.cRadioGroup:
                case CUICore.pluginType.cCheckbox:
                case CUICore.pluginType.cTextarea:
                case CUICore.pluginType.cButton:
                    return kind;
                default:
                    return CUICore.pluginType.unkonw;
            }
        }
        else {
            return CUICore.pluginType.unkonw;
        }
    };


    $.fn.getValue = function () {
        var self = $(this).eq(0);
        if (self.is("[kind]")) {
            var kind = self.kind();
            switch (kind) {
                //for textbox and text area, If has tip class, value is empty                       
                case CUICore.pluginType.cTextbox:
                case CUICore.pluginType.cTextarea:
                    {
                        if (self.hasClass("tip")) {
                            return "";
                        }
                        else {
                            return self.val();
                        }
                    }
                    //for drop down list will return the selected item's value                                                                            
                case CUICore.pluginType.cDropdownList:
                    return self.val();
                    break;
                //for radio group will return the selected radio item value                                                                                                   
                case CUICore.pluginType.cRadioGroup:
                    if (self.is("[name]")) {
                        var name = self.attr("name");
                        return $('input:radio[name=' + name + ']:checked').val();
                    }
                    break;
                //for checkbox will if checked return true, unchecked return false. ignore the value attribute.                                                                                                   
                case CUICore.pluginType.cCheckbox:
                    if (self.is(":checked")) {
                        return true;
                    }
                    else {
                        return false;
                    }
                    //for others return value attribute
                default:
                    return self.val();
            }
        }
        return self.val();
    };

    /****************************** FROM Submit & Validate ******************************/

    $.fn.submitValidate = function (ignoreValidation) {
        var params = {};
        var pass = true;
        var self = $(this);

        //validate and get params from input
        self.find("[kind]").each(function () {
            var self = $(this);
            var kind = self.kind();
            //ignore validate for [hide, disabled and radio]
            if (!self.hasClass("hide") && !self.is(":disabled")) {
                //is button or radio group
                if (kind != CUICore.pluginType.cRadioGroup && kind != CUICore.pluginType.cButton) {
                    if (ignoreValidation !== true && CUIPage.prototype.ShowValidate(self) !== true) {
                        pass = false;
                    }
                    if (self.is("[id]")) {
                        params[self.attr("id")] = self.getValue();
                    }
                }
            }
        });

        //validate and get params from radio
        self.find("input:radio").each(function () {
            var self = $(this);
            if (self.is("[name]")) {
                var key = self.attr("name");
                if (params[key] === undefined) {
                    if (ignoreValidation !== true && CUIPage.prototype.ShowValidate($('input:radio[name=' + key + ']')) !== true) {
                        pass = false;
                    }
                    var value = $('input:radio[name=' + key + ']').getValue();
                    if (value !== undefined) {
                        params[key] = $('input:radio[name=' + key + ']').getValue();
                    }
                    else {
                        params[key] = "";
                    }
                }
            }
        });

        if (pass) {
            return params;
        }
        else {
            return null;
        }
    };

    /****************************** UI PLUGIN ***************************************/

    $.fn.sidebar = function (options) {
        if ($(this).length > 0) {

            //Get the default
            var self = $(this).eq(0);

            var defaults = {
                defaultHide: true,
                onShow: null,
                onHide: null,
                position: "right"
            };

            self.opts = $.extend({}, defaults, options);
            self.css("position", "fixed");

            if (self.opts.position === "top" || self.opts.position === "bottom") {
                if (self.opts.defaultHide === true) {
                    self.css(self.opts.position, "-" + self.height() + "px");
                }
                else {
                    self.css(self.opts.position, self.height() + "px");
                }
            }
            if (self.opts.position === "left" || self.opts.position === "right") {
                if (self.opts.defaultHide === true) {
                    self.css(self.opts.position, "-" + self.width() + "px");
                }
                else {
                    self.css(self.opts.position, self.width() + "px");
                }
            }
            self.hover(
            function () {
                self.show();
            },
            function () {
                self.hide();
            });
            //show the sidebar
            self.hide = function () {
                var animateOption = {};
                if (self.opts.position === "top" || self.opts.position === "bottom") {
                    animateOption[self.opts.position] = '-' + self.height();
                }
                if (self.opts.position === "left" || self.opts.position === "right") {
                    animateOption[self.opts.position] = '-' + self.width();
                }
                self.stop().animate(
                animateOption,
                800,
                function () {
                    if (typeof self.opts.onShow === "function") {
                        self.opts.onHide();
                    }
                });
            };
            //hide the sidebar
            self.show = function () {
                var animateOption = {};
                if (self.opts.position === "top" || self.opts.position === "bottom") {
                    animateOption[self.opts.position] = 0;
                }
                if (self.opts.position === "left" || self.opts.position === "right") {
                    animateOption[self.opts.position] = 0;
                }
                self.stop().animate(
                animateOption,
                800,
                function () {
                    if (typeof self.opts.onShow === "function") {
                        self.opts.onShow();
                    }
                });
            }
        }
        else {
            if (CUICore.debug) {
                alert("The sidebar cannot be found!");
            }
        }
        return self;
    };

})(jQuery);

